package cn.cnlee.app.base;


import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.tqzhang.stateview.stateview.BaseStateControl;

import java.util.ArrayList;
import java.util.List;

import cn.cnlee.app.config.Constants;
import cn.cnlee.arch.base.AbsViewModel;
import cn.cnlee.arch.base.BaseFragment;
import cn.cnlee.arch.event.LiveBus;
import cn.cnlee.arch.util.ClassUtil;
import cn.cnlee.arch.util.Logger;
import cn.cnlee.arch.view.stateview.ErrorState;
import cn.cnlee.arch.view.stateview.LoadingState;
import cn.cnlee.arch.view.stateview.StateConstants;


/**
 * Fragment的抽象类（ViewModel、LiveData、生命周期等相关）
 */
public abstract class AbsLifecycleFragment<T extends AbsViewModel> extends BaseFragment {

    protected T mViewModel;//当前Fragment持有的ViewModel

    private List<Object> eventKeys = new ArrayList<>();//当前Fragment所有LiveBus事件eventKey集合
    protected boolean needReloadData = false;

    @Override
    public void initView(Bundle state) {
        mViewModel = VMProviders(this, (Class<T>) ClassUtil.getTypeInstance(this, 0));
        if (null != mViewModel) {
            dataObserver();
            mViewModel.mRepository.loadState.observe(this, observer);
            LiveBus.get().getChannel(Constants.LOGIN_ACTION_NOTIFY_KEY).observe(this, loginDTO -> {
                needReloadData = true;
            });

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstVisible || needReloadData) {
            lazyLoad();
            mIsFirstVisible = false;
            needReloadData = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mIsFirstVisible = true;
    }

    /**
     * 创建viewModel的方法
     *
     * @param fragment   当前Owner
     * @param modelClass The class of the ViewModel
     * @param <T>        The type parameter for the ViewModel.
     * @return A ViewModel that is an instance of the given type
     */
    protected <T extends ViewModel> T VMProviders(BaseFragment fragment, @NonNull Class<T> modelClass) {
        return new ViewModelProvider(fragment, new ViewModelProvider.AndroidViewModelFactory(activity.getApplication())).get(modelClass);

    }

    /**
     * Repository中数据观察者处理方法
     */
    protected void dataObserver() {
    }

    /**
     * 在LiveBus中订阅Repository请求返回的postData事件（eventKey一一对应）
     *
     * @param eventKey
     * @param tag
     * @param tClass
     * @param <T>
     * @return
     */
    protected <T> MutableLiveData<T> registerSubscriber(Object eventKey, String tag, Class<T> tClass) {
        String event;
        if (TextUtils.isEmpty(tag)) {
            event = (String) eventKey;
        } else {
            event = eventKey + tag;
        }
        eventKeys.add(event);
        return LiveBus.get().getChannel(eventKey, tag, tClass);
    }

    protected <T> MutableLiveData<T> registerSubscriber(Object eventKey, Class<T> tClass) {
        return registerSubscriber(eventKey, null, tClass);
    }

    @Override
    protected void onStateRefresh() {
        showLoading();
    }

    /**
     * 获取仓库数据（网络数据或本地数据）
     */
    protected void getRepoData() {
    }

    protected void showError(Class<? extends BaseStateControl> stateView, Object tag) {
        loadManager.showStateView(stateView, tag);
    }

    protected void showError(Class<? extends BaseStateControl> stateView) {
        showError(stateView, null);
    }

    protected void showSuccess() {
        loadManager.showSuccess();
    }

    protected void showLoading() {
        loadManager.showStateView(LoadingState.class);
    }


    /**
     * StateView视图状态监听
     */
    protected Observer observer = new Observer<String>() {
        @Override
        public void onChanged(@Nullable String state) {
            if (!TextUtils.isEmpty(state)) {
                if (StateConstants.ERROR_STATE.equals(state)) {
                    showError(ErrorState.class, "2");
                } else if (StateConstants.NET_WORK_STATE.equals(state)) {
                    showError(ErrorState.class, "1");
                } else if (StateConstants.NO_LOGIN_STATE.equals(state)) {
                    showError(ErrorState.class, "-1");
                } else if (StateConstants.LOADING_STATE.equals(state)) {
                    showLoading();
                } else if (StateConstants.SUCCESS_STATE.equals(state)) {
                    showSuccess();
                } else if (StateConstants.NOT_DATA_STATE.equals(state)) {
                    showError(ErrorState.class, "0");
                }
            }
        }
    };

    /**
     * 登录成功后事件（可能需要重新请求）
     */
    protected void loginNext() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        clearEvent();
    }

    /**
     * 清理当前Fragment所有LiveBus事件
     */
    private void clearEvent() {
        if (eventKeys != null && eventKeys.size() > 0) {
            for (int i = 0; i < eventKeys.size(); i++) {
                LiveBus.get().clear(eventKeys.get(i));
            }
        }
    }
}
